package evi.com.evi.login;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.util.regex.Pattern;

import evi.com.evi.R;
import evi.com.evi.activity.HomeActivity;
import evi.com.evi.application.MyApplication;
import evi.com.evi.utils.AppUtils;
import evi.com.evi.utils.ConnectUtil;
import evi.com.evi.utils.ContentUtils;
import evi.com.evi.utils.JSONUtils;
import evi.com.evi.utils.RegexUtils;
import evi.com.evi.utils.SPUtil;
import evi.com.evi.utils.ScreenUtils;
import evi.com.evi.utils.ToastUtils;
import evi.com.evi.view.TimeButton;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static org.bouncycastle.crypto.tls.ConnectionEnd.client;

public class LoginByCodeActivity extends Activity implements
		OnClickListener {

	private static final String TAG = "TAG";

	private View view;
	private boolean SEND = false;

	private TextView tv_title;
	private EditText et_phone;
	private EditText et_vali;
	private View ll01;
	private TimeButton timeButton;
	private TextView tv_sure;

    private OkHttpClient client;
    private JSONUtils jsonUtil;

	private Dialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ScreenUtils.setTranStatus(this, false, Color.parseColor("#FF6600"));
		MyApplication.getInstance().addActivity(this);
		view = View.inflate(this, R.layout.activity_login_by_code, null);
		setContentView(view);

		initView();
		timeButton.setTextDes("获取验证码").setTextTime(60*1000).continueStatue();
		timeButton.setOnClickListener(this);
		initData();
	}

	private void initView() {
		tv_title = (TextView) findViewById(R.id.tv_title);
		et_phone = (EditText) findViewById(R.id.et_phone);
		et_vali = (EditText) findViewById(R.id.et_vali);

		ll01 = findViewById(R.id.ll01);

		timeButton = (TimeButton) view.findViewById(R.id.timeBt);
		tv_sure = (TextView) view.findViewById(R.id.tv_sure);

        client = new OkHttpClient();

        jsonUtil = new JSONUtils();
	}

	private void initData() {
		view.findViewById(R.id.forget_bar_back_left).setOnClickListener(this);
		timeButton.setOnClickListener(this);
		tv_sure.setOnClickListener(this);

		et_phone.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (RegexUtils.isRegex(et_phone.getText().toString(),
						RegexUtils.RX_Mobile)
						&& !TextUtils.isEmpty(et_phone.getText().toString())) {
					SEND = true;
				} else {
					SEND = false;
				}
			}
		});
	}

	private String phoneNo;
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.forget_bar_back_left:
				finish();
				break;
		case R.id.timeBt:
			if (SEND) {
				//此处发送验证码
                phoneNo = et_phone.getText().toString();

                requestVerifyCode(phoneNo);
			} else {
				timeButton.initStatue();
				ToastUtils.showMsg(LoginByCodeActivity.this, "手机格式不对,请重新输入");
			}
			break;
		case R.id.tv_sure:// 确定
			phoneNo = et_phone.getText().toString();
			String smsCode = et_vali.getText().toString();
			if (TextUtils.isEmpty(phoneNo)) {
				ToastUtils.showMsg(LoginByCodeActivity.this, "请输入手机号码");
				return;
			} else if (!SEND) {
				ToastUtils.showMsg(LoginByCodeActivity.this, "手机格式不对,请重新输入");
				return;
			} else if (TextUtils.isEmpty(smsCode)) {
				ToastUtils.showMsg(LoginByCodeActivity.this, "请输入验证码");
				return;
			}
			boolean flag_1 = TextUtils.isEmpty(et_phone.getText().toString());
			boolean flag_2 = TextUtils.isEmpty(et_vali.getText().toString());

			if (flag_1 && flag_2) {
				ToastUtils.showMsg(LoginByCodeActivity.this,"请填写完整信息");
			} else {
				login();
			}
			break;
		}
	}
	private void login() {
		dialog = AppUtils.getLoadingDialog(this, "提示", "正在登录，请稍后");
		dialog.show();
		String code = et_vali.getText().toString();
		Log.e(TAG, "login: " + token);
		String message = "?phoneNo=" + phoneNo + "&code=" + code;
		client = new OkHttpClient();
		Request request = new Request.Builder()
				.addHeader("token",token)
				.url(ContentUtils.message_login_url + message)
				.build();

		client.newCall(request).enqueue(new Callback() {
			@Override
			public void onFailure(Call call, IOException e) {
//				toast("网络信号不佳，加载失败");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(ConnectUtil.isConnect(LoginByCodeActivity.this)){
                            toast("网络信号不佳，加载失败");
                        } else {
                            toast("网络未联接，请检查");
                        }
                    }
                });
				dismiss();
			}

			@Override
			public void onResponse(Call call, Response response) throws IOException {
				String dataMessage = response.body().string();
				Log.e(TAG, "onResponse: " + dataMessage );
				if (jsonUtil.validate(dataMessage)) {
					JSONObject jsonObject = JSON.parseObject(dataMessage);
					Boolean success = jsonObject.getBoolean("success");
					if (success) {
						Intent intent = new Intent(LoginByCodeActivity.this,HomeActivity.class);
						startActivity(intent);
						finish();
					} else {
						toast(jsonObject.getString("message"));
					}
					dismiss();

				}
			}
		});

	}

	private String token;
    //获取验证码信息，进行验证码请求
    private void requestVerifyCode(String phoneNo) {
		dialog = AppUtils.getLoadingDialog(this, "提示", "正在获取验证码，请稍后");
		dialog.show();
        String message = "?phoneNo=" + phoneNo;
        client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(ContentUtils.message_url + message)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                toast("网络信号不佳，加载失败");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(ConnectUtil.isConnect(LoginByCodeActivity.this)){
                            toast("网络信号不佳，加载失败");
                        } else {
                            toast("网络未联接，请检查");
                        }
                    }
                });
				dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String dataMessage = response.body().string();
                if (jsonUtil.validate(dataMessage)) {
                    Log.e("TAG", dataMessage);
                    JSONObject jsonObject = JSON.parseObject(dataMessage);
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        token = jsonObject.getJSONObject("data").getString("token");
                        SPUtil.setString(LoginByCodeActivity.this, "token", token);
                    } else {
                        toast(jsonObject.getString("message"));
					}
                }
				dismiss();
			}
        });
    }

	/**
	 * 是否有特殊字符
	 * 
	 * @param password
	 * @return
	 */
	public static boolean hasSpecialChar(String password) {
		String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
		return Pattern.compile(regEx).matcher(password).find();
	}
    private void toast(final String string){
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(LoginByCodeActivity.this, string, Toast.LENGTH_SHORT).show();
            }
        });
    }
	private void dismiss(){
		this.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				dialog.dismiss();
			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		MyApplication.getInstance().deleteActivity(this);
	}
}
